// eslint-disable-next-line
import Http from 'axios'
import qs from 'qs'
import { Message } from 'element-ui'
import { getToken, removeToken } from '../util/auth'
if (process.env.NODE_ENV === 'production') {
  Http.defaults.baseURL = 'https://film.ishareu.cn/api'
} else {
  Http.defaults.baseURL = 'http://127.0.0.1:3000'
}

Http.defaults.timeout = 30000
Http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
Http.defaults.transformRequest = [
  data => {
    return qs.stringify(data)
  }
]

// 请求类
class ApiService {
  constructor() {
    this.interceptorsOfReq()
    this.interceptorsOfRes()
  }

  get(url, params = {}) {
    if (params) {
      return Http.get(url, {
        params
      }).then(res => res.data)
    }
    return Http.get(url).then(res => res.data)
  }

  post(url, bodyParams = {}, params = {}) {
    if (Object.keys(params).length > 0) {
      for (let key in params) {
        url += `&${key}=${params[key]}`
      }
    }
    return Http.post(url, bodyParams).then(res => res.data)
  }

  interceptorsOfReq() {
    return Http.interceptors.request.use(
      config => {
        let token = getToken()
        if (token) {
          config.headers['token'] = token
        }
        return config
      },
      err => {
        return Promise.reject(err)
      }
    )
  }

  interceptorsOfRes() {
    Http.interceptors.response.use(
      function(response) {
        let res = response.data
        if (res.code === 0) {
          return response
        } else if (res.code === -1) {
          Message({
            message: res.msg,
            type: 'error',
            duration: 5 * 1000
          })
          return Promise.reject('error')
        } else if (res.code === 401) {
          Message({
            message: res.msg,
            type: 'error',
            duration: 5 * 1000
          })
          return Promise.reject('error')
          removeToken()
        }
      },
      function(error) {
        Message({
          message: error.message,
          type: 'error',
          duration: 5 * 1000
        })
        return Promise.reject(error)
      }
    )
  }
}

// 导出一个对象
export default new ApiService()
